import Vue from 'vue'
import Router from 'vue-router'

import store from '@/store/index'
import { Message } from 'element-ui';

// 路由模版
import layout from './routes/layout'

let RouterFn = new Router({
  mode:'history',
  base:'/',
  routes:routersArr(),
  scrollBehavior: () => ({ y: 0 }),
})

const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}

// 全局路由钩子函数 对全局有效
RouterFn.beforeEach((to, from, next) => {
  let token = store.getters['user/getToken']
  let meta = to.meta
  let checked = meta && meta.checked

  // 判断是否需要检测登陆
  if(!checked){
    // 不需要检测登陆直接进入
    let name = to.name
    if(token && (name == 'login' || name == 'reg'))return next(from)

    next()
  }else{
    // 需要检测登陆判断登陆
    if(!token){
      // 未登录
      Message.error('游客无访问权限，请先登录')
      setTimeout(()=>{
        next('/')
      },1500)
    }else{
      // 登陆
      next()
    }
  }

})

function routersArr() {
  let routes = layout
      // .concat(common)
  ;
  return routes
}

Vue.use(Router)
export default RouterFn;
